package com.example.jf.jfapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.Log;
import android.view.View;

import com.example.jf.jfapp.activity.base.BaseActivity;
import com.example.jf.jfapp.bean.bean.SendCommentRequestBean;
import com.example.jf.jfapp.bean.response.SendCommentResponse;
import com.example.jf.jfapp.receiver.CommentReceiver;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.OkHttpUtils;
import com.example.jf.jfapp.utils.RequestUtils;
import com.google.gson.Gson;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.example.jf.jfapp.CommentActivity.STATU_ID_KEY;

/**
 * Created by jf on 2017/7/29.
 */

public class CommentEditActivity extends BaseActivity {
    public final static int COMMENT_RESULT_CODE = 222;
    public final static String COMMENT_STATU = "statu";


    @BindView(R.id.et_send_content)
    AppCompatEditText etSendContent;
    private String statuID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_edit);
        ButterKnife.bind(this);
        getData();
    }

    @Override
    public void getData() {
        statuID = getIntent().getStringExtra(STATU_ID_KEY);
    }

    @OnClick({R.id.tv_cancle, R.id.tv_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cancle:
                finish();
                break;
            case R.id.tv_send:
                if (etSendContent.getText().toString().equals("")) {
                    showToast("评论不能为空");
                } else {
                    SendCommentRequestBean mRequestBean = new SendCommentRequestBean();
                    mRequestBean.setUserId(AppConfigUtils.getInstance().getLoginInfo(CommentEditActivity.this).getObjectId());
                    statuID = getIntent().getStringExtra(STATU_ID_KEY);

                    mRequestBean.setStatusId(statuID);
                    mRequestBean.setContent(etSendContent.getText().toString());
                    sendComment(mRequestBean);
                    showProgressDialog("提交评论中...");
                }
                break;
        }
    }

    /**
     * 发送评论
     * @param mRequestBean
     */
    private void sendComment(SendCommentRequestBean mRequestBean) {
        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();

        Request request = RequestUtils.requestPOST(mRequestBean, Constant.URL.SENDCOMMENT);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("评论失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e(TAG, "onResponse: " + result);

                final SendCommentResponse sendCommentResponse = new Gson().fromJson(result, SendCommentResponse.class);

                //重新构建评论数据
                final CommentReceiver.CommentBean commentBean = new CommentReceiver.CommentBean();
                commentBean.setObjectId(sendCommentResponse.getResult().getComment().getObjectId());
                commentBean.setContent(sendCommentResponse.getResult().getComment().getContent());
                commentBean.setCreatedAt(sendCommentResponse.getResult().getComment().getCreatedAt());
                //注意，接口没有返回动态id，需要自己添加，该值特别重要，接受广播的类需要拿到该值来匹配对应的动态，
                //以便设置评论个数
                commentBean.setStatuId(statuID);

                CommentReceiver.CommentBean.UserBean userBean = new CommentReceiver.CommentBean.UserBean();
                userBean.setObjectId(sendCommentResponse.getResult().getComment().getUser().getObjectId());
                commentBean.setUser(userBean);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("评论成功");
                        Intent intent = new Intent();
                        intent.putExtra(COMMENT_STATU, true);
                        setResult(COMMENT_RESULT_CODE, intent);

                        sendCommentBroadcast(commentBean);
                        finish();
                    }
                });

            }
        });
    }


    /**
     * 发送评论成功的广播
     * <p>接受到广播后，需要获取广播携带的评论数据
     * <p>判断携带的评论数据 的【动态id】跟列表中的【动态id】相同，那么就需要更新该条目数据
     */
    public void sendCommentBroadcast(CommentReceiver.CommentBean commentBean) {
        Intent intent = new Intent(CommentReceiver.Action.ACTION_COMMENT_SUCCESSFUL);
        intent.putExtra(CommentReceiver.NEW_COMMENT_KEY, commentBean);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

}
